<?php
//自定义函数


/**
 * 返回状态/信息的数组
 */
if( !function_exists('retArray')){
	function retArray($status = 300, $text = ""){
		if($status * 1 != 0){
			$ret['status'] = $status * 1;
		}else{
			$ret['status'] = 300;
		}
		$ret['text'] = $text;
		return $ret;
	}
}

/**
 * API 返回数据
 */
if( !function_exists('echo_success')){
	function echo_success($errmsg){
		$ret['errcode'] = 0;
		$ret['errmsg'] = $errmsg;
		exit(json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
	}
}

/**
 * API 返回数据
 */
if( !function_exists('echo_error')){
	function echo_error($errcode, $errmsg){
		$ret['errcode'] = $errcode * 1;
		$ret['errmsg'] = $errmsg;
		exit(json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
	}
}

/**
 * API 获取参数值
 */
if( !function_exists('get_param')){
	function get_param($request, $need_params, $optional_params){
		$data = json_decode(base64_decode($request->data),true);	//解析数据
		$param = [];	//初始化数据
		foreach($optional_params as $k => $v){
			if(isset($data[$v]) && $data[$v]!==""){
				$param[$v] = $data[$v];
			}else{
				$param[$v] = null;
			}
		}
		foreach($need_params as $k => $v){
			if(isset($data[$v]) && $data[$v]!==""){
				$param[$v] = $data[$v];
			}else{
				echo_error(1000,"缺少参数".$v."！");
			}
		}

		return $param;
	}
}

/**
 * 判断文件类型是否为图片
 */
if( !function_exists('isImage')){
	function isImage($type = null){
		if(empty($type)){   //参数：文件类型是否存在
			return false;
		}else{
			$imageType = [
				'image/gif',
				'image/jpeg',
				'image/png',
				'image/bmp'
			];
			if(in_array($type, $imageType)){
				return true;
			}
			return false;
		}
	}
}

/**
 * 删除文件
 */
if( !function_exists('delFile')){
	function delFile($path = null){
		if( !empty($path)){
			$path = './'.$path;
			if(file_exists($path)){
				unlink($path);
			}
		}
	}
}

/**
 * 删除存放在数组中的文件文件
 */
if( !function_exists('delFileArray')){
	function delFileArray($arr = []){
		if( !empty($arr)){
			foreach($arr as $k => $v){
				delFile($v);
			}
		}
	}
}

/**
 * 查询IP所在地址
 */
if( !function_exists('getIPLoc_sina')){
	function getIPLoc_sina($queryIP){
		$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;
		$ch = curl_init($url);
		//curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
		$location = curl_exec($ch);
		$location = json_decode($location);
		curl_close($ch);

		$loc = "";
		if($location === false){
			return "";
		}
		if(empty($location->desc)){
			$loc = $location->province.$location->city.$location->district.$location->isp;
		}else{
			$loc = $location->desc;
		}
		return $loc;
	}
}

/**
 * 图片缩放
 * filepath		图片路径，例："./assets/image/timg.gif"
 * widthMax		图片最大宽
 * heightMax	图片最大高
 */
if( !function_exists('imageShrink')){
	function imageShrink($filepath='',$widthMax=10000,$heightMax=10000){

		$widthMax = ( !empty($widthMax) ? $widthMax*1 : 1 );
		$heightMax = ( !empty($heightMax) ? $heightMax*1 : 1 );

		$pathinfo = pathinfo($filepath);
		$extension = strtolower($pathinfo['extension']);	//后缀名
		$typeArr = ['jpg'=>'jpeg','jpeg'=>'jpeg','png'=>'png','gif'=>'gif'];	//图片后缀名与图片类型组合

		if(empty($typeArr[$extension])){		//如果不是图片，则退出
			return false;
		}else{
			$imgType = $typeArr[$extension];	//通过图片后缀名获取图片类型
		}

		$originalImg = call_user_func('imagecreatefrom'.$imgType,$filepath);
		$originalWidth = imagesx($originalImg);		//原图宽
		$originalHeight = imagesy($originalImg);	//原图高
		$ratio = $originalWidth/$originalHeight;	//宽高比
		//echo $originalWidth.'*'.$originalHeight;die;	//打印原图宽高
		//dd($ratio);								//打印原图宽高比
		if($originalWidth<=$widthMax && $originalHeight<=$heightMax){		//原图宽高都在要求内
			//dd(1);
			$width = $originalWidth;
			$height = $originalHeight;
		}elseif($originalWidth>$widthMax && $originalHeight<=$heightMax){	//宽超出要求，以最大宽为准
			//dd(2);
			$width = $widthMax;
			$height = $width/$ratio;
		}elseif($originalWidth<=$widthMax && $originalHeight>$heightMax){	//高超出要求，以最大高为准
			//dd(3);
			$height = $heightMax;
			$width = $height*$ratio;
		}else{																//宽高都超出要求，以小比例的边为准
			$ratioMax = $widthMax/$heightMax;
			if($ratio < $ratioMax){
				//dd(4);
				$height = $heightMax;
				$width = $height*$ratio;
			}else{
				//dd(5);
				$width = $widthMax;
				$height = $width/$ratio;
			}
		}
		$img = imagecreatetruecolor($width,$height);	//准备一个黑色画布
		$color = imagecolorallocate($img,255,255,255);   //准备白色
		$color = imagecolorallocatealpha($img,255,255,255,127);
		imagefill($img,0,0,$color);									//从x:0;y:0坐标开始填充颜色背景
		imagecopyresampled($img,$originalImg,0,0,0,0,$width,$height,$originalWidth,$originalHeight);

		call_user_func('image'.$imgType,$img,$filepath);	//输出图像，保存到原路径
		imagedestroy($img);
		imagedestroy($originalImg);
	}
}

/**
 * 遍历public下的某个文件夹
 * dirpath		要遍历的文件夹路径，例："/upload/image/20170916"
 * widthMax		图片最大宽
 * heightMax	图片最大高
 */
if( !function_exists('imageShrinkDir')){
	function imageShrinkDir($dirpath='',$widthMax=10000,$heightMax=10000){
		$publicPath = public_path();
		foreach(scandir($publicPath.$dirpath) as $afile)
		{
			if($afile=='.'||$afile=='..') continue;
			if(is_dir($publicPath.$dirpath.'/'.$afile))
			{
				imageShrinkDir($dirpath.'/'.$afile,$widthMax,$heightMax);
			} else {
				$filepath = '.'.$dirpath.'/'.$afile;	//获取文件路径
				echo $filepath."<br>";				//打印所有路径
				imageShrink($filepath,$widthMax,$heightMax);	//压缩所有图片文件
			}
		}
	}
}




